import React, { Component } from 'react'
// 过渡动画组件 -- 它还是需要css样式的加持
// CSSTransition in:boolean进出场 timeout:number动画时长ms
// TransitionGroup 列表过渡动画，对于新增或删除列表项数据在展示时有动画效果
// 注：TransitionGroup里面要包裹CSSTransition，而且CSSTransition中的in属性要更换为key属性，且key的值唯一的
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import './style/animate.css'

class App extends Component {
  state = {
    title: '',
    todos: []
  }

  onEnter = ({ key }) => {
    if (key === 'Enter') {
      // 回车事件
      this.setState(
        state => ({
          todos: [...state.todos, { id: Date.now(), title: state.title }]
        }),
        () => {
          this.setState({ title: '' })
        }
      )
    }
  }
  // 删除项
  delItem = id => {
    this.setState(state => ({
      // 删除操作
      todos: state.todos.filter(item => item.id !== id)
    }))
  }

  render() {
    return (
      <div>
        <div>
          <input
            type="text"
            value={this.state.title}
            onChange={e => this.setState({ title: e.target.value.trim() })}
            onKeyUp={this.onEnter}
          />
        </div>
        <hr />
        <TransitionGroup>
          {this.state.todos.map(item => (
            <CSSTransition key={item.id} timeout={300} classNames="fade" unmountOnExit>
              <div>
                <span>{item.title}</span> --
                <span onClick={() => this.delItem(item.id)}>删除</span>
              </div>
            </CSSTransition>
          ))}
        </TransitionGroup>
      </div>
    )
  }
}

export default App
